//=============================================基础处理函数=============================
var toolEvent = {
    emptyString : function(value){
        return value?value:"";
    }
}
//========================================================树加载操作函数=====================n=======================
var TreeNodesObj = {
    _zNodes : regionData()
}

var zTreeLoadEvent = {
    zTreeObj : {},
    ztreeSetting : {
        view: {
            dblClickExpand: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pid",
                rootPId: ""
            }
        }
    },

    mapTreeLoad : function(){
        // 初始化ztree
        zTreeLoadEvent.zTreeObj = $.fn.zTree.init($("#deptTree"), zTreeLoadEvent.ztreeSetting, treeNode);
        var ztreeNode = zTreeLoadEvent.zTreeObj.getNodes();
        zTreeLoadEvent.zTreeObj.expandNode(ztreeNode[0]);
        return zTreeLoadEvent.zTreeObj;
    }
}
/*********========map 地图上的点击事件  （右键和左键点击事件）========***************/
var mennu = {
    /**lis {name:'',fn:function(){}}**/
    menuContainer : document.getElementById("contextmenu_container"),
    createMenu : function(lis){
        var menuContainer = this.menuContainer;
        var menu_overlay = mapLoadEvent.menu_overlay;
        var clickCoordinate = mapClickEvent.clickCoordinate;
        var clickFeature = mapClickEvent.clickFeature;
        menuContainer.innerHTML = "";
        if(lis.length == 0){
            menu_overlay.setPosition(undefined);
            return false;
        }
        var ulEl = document.createElement("ul");
        for(var i=0;i<lis.length;i++){
            var liEl = document.createElement("li");
            var _tmpl = lis[i];
            liEl.innerHTML = lis[i].name;
            liEl.clickMenod =  _tmpl.fn;
            liEl.menuObjStr = encodeURIComponent(encodeURIComponent(JSON.stringify(_tmpl)));
            liEl.onclick = function(e){
                menu_overlay.setPosition(undefined);
                var lifn = this.clickMenod;
                var menuObj = JSON.parse(decodeURIComponent(decodeURIComponent(this.menuObjStr)));
                if(typeof lifn == "function"){
                    lifn(clickCoordinate,clickFeature,menuObj);
                }else if(typeof lifn == "string"){
                    var callback = eval(lifn);
                    new callback(clickCoordinate,clickFeature,menuObj);
                }
            }
            ulEl.appendChild(liEl);
        }
        menuContainer.appendChild(ulEl);
    }
}
//========================================================二维地图相关操作函数=====================n=======================



var mapLoadEvent = {
    layer : {},
    clickMap : {},
    map : {},
    vectorLayer : {},
    menu_overlay : {},
    overlay : {},
    overlayContent : {},
    deviceList : {},
    deviceTypeStyle : {},
    draw: {},
    drawSource: {},
    drawStyle: {},
    drawVector: {},
    circleCenter: {},
    select: {},
    selectedFeatures: {},
    //二维地图map加载
    mapInit : function(defaultImage){
        extent = [0, 0, 1350, 692];      //图片图层四至
        projection = new ol.proj.Projection({       //定义坐标系
            code: 'xkcd-image',
            units: 'pixels',
            extent: extent
        });
        mapLoadEvent.map =  new ol.Map({
            layers: [
                new ol.layer.Image({
                    source: new ol.source.ImageStatic({
                        //url: '/public/maps/103.jpg',    //地址
                        url: defaultImage,    //地址
                        projection: projection,
                        imageExtent: extent
                    })
                })
            ],
            target: 'map',
            view: new ol.View({
                projection: projection,
                center: ol.extent.getCenter(extent),
                zoom: 2,
                minZoom: 1,
                maxZoom: 6
            }),
            interactions:ol.interaction.defaults({
                doubleClickZoom: false               //禁用双击放大
            })
        });
        var vectorLayer = new ol.layer.Vector({
            source: new ol.source.Vector()
        });
        mapLoadEvent.map.addLayer(vectorLayer);
        mapLoadEvent.vectorLayer = vectorLayer;

        mapLoadEvent.menu_overlay = mapLoadEvent.loadMenuOverlay();
        mapLoadEvent.map.addOverlay(mapLoadEvent.menu_overlay);

        mapLoadEvent.overlay = mapLoadEvent.loadOverlay();
        mapLoadEvent.map.addOverlay(mapLoadEvent.overlay);


        mapLoadEvent.pointShareOverlay = mapLoadEvent.loadShareOverlay();
        mapLoadEvent.map.addOverlay(mapLoadEvent.pointShareOverlay);

        mapClickEvent.clickEvent();
        return mapLoadEvent.map;
    },
    //记载二维地图上的右键弹出框
    loadMenuOverlay : function(){
        var menu_overlay = new ol.Overlay({
            element: document.getElementById("contextmenu_container"),
            positioning: 'center-center'
        });
        return menu_overlay;
    },
    //加载二维地图上的闪烁点的图层信息
    loadShareOverlay : function(){
        var point_div = document.getElementById("css_animation");
        var point_overlay = new ol.Overlay({//定义为全局变量
            element: point_div,
            positioning: 'center-center'
        });
        return point_overlay;

    },
    //记载二维地图上的弹出提示框
    loadOverlay : function(){
        var container = document.getElementById('popup');
        var content = document.getElementById('popup-content');
        var closer = document.getElementById('popup-closer');
        var overlay = new ol.Overlay({
            element: container,
            autoPan: true,
            autoPanAnimation: {
                duration: 250
            }
        });

        closer.onclick = function() {
            overlay.setPosition(undefined);
            closer.blur();
            return false;
        };
        mapLoadEvent.overlayContent = content;
        return overlay;
    },
    //加载对应的静态图片
    loadImageLayer : function(treeNode){
        //去除报警效果显示
        var point_overlay = mapLoadEvent.pointShareOverlay;
        point_overlay.setPosition(undefined);
        if(treeNode.imagePath){
            mapLoadEvent.clickMap = treeNode;
            var map = mapLoadEvent.map;
            var imagePath ='/public/maps'+treeNode.imagePath;
            var imageStaic = map.getLayers().item(0);
            imageStaic.setSource(
                new ol.source.ImageStatic({
                    url: imagePath,    //地址
                    // url: "../images/two_map.png",    //地址
                    projection: projection,
                    imageExtent: extent
                })
            );
        }else{
            mapLoadEvent.clickMap = undefined;
            mapLoadEvent.layer.alert(treeNode.name+'---地图未上传,请在后台进行配置！！', {icon: 2});
        }

    },
    //记载二维地图上对应的设备
    loadDeviceLayer : function(mapGuid){
        this.deviceList = {};
        var deviceList = this.AjaxDeviceList(mapGuid);
        this.deviceList = deviceList;
        this.deviceLoadVector(deviceList);
    },
    //ajax获取二对维地图上的设备
    AjaxDeviceList : function(mapGuid){
        var dataList = [];
        Ajax({
            "url":"/mapdevice/getDevcieByMapGuid/auth.shtml",
            "param" : {"mapGuid":mapGuid},
            successBack: function(data){
                dataList = data;
            }
        });
        return dataList;
    },
    //页面加载对应设备
    deviceLoadVector : function(deviceList){
        var deviceTypeStyle = this.deviceTypeStyle;
        var vectorLayer = mapLoadEvent.vectorLayer;
        vectorLayer.getSource().clear();
        var userids = [],checkids=[];
        $(":checkbox[name='deviceType']").each(function(){
            userids.push($(this).val());
            if($(this).is(":checked")){
                checkids.push($(this).val());
            }
        });

        var checkeVal = checkids.toString(),AlltypeVal = userids.toString();
        $(deviceList).each(function(index){
            var tmp = this;
            var deviceType="";
            var dtype = tmp.typeCode;
            var feature = new ol.Feature({
                geometry: new ol.geom.Point([parseFloat(tmp.posX),parseFloat(tmp.posY)])
            });
            feature.setId(tmp.deviceUuid);
            feature.setProperties(tmp);
            var photoUrl="";
            if(tmp.typeCode=="JK"){
                if(tmp.dbcType=="1"){
                    photoUrl="/JK/2019080811203790cur_sxt.png";
                }else if(tmp.dbcType=="2"){
                    photoUrl="/JK/2019101419484880球机.png";
                }else if(tmp.dbcType=="3"){
                    photoUrl="/JK/20191014194411292半球.png";
                }else if(tmp.dbcType=="4"){
                    photoUrl="";
                }
            }else{
                photoUrl=tmp.deviceIcon;
            }
            deviceType = photoUrl;
            debugger
            var style ;
            if(!deviceTypeStyle[deviceType]){
                style = new ol.style.Style({
                    image: new ol.style.Icon({
                        src: '/public/devices'+photoUrl
                        //src: "../images/device.png"
                    })
                });
                deviceTypeStyle[deviceType] = style;
            }else{
                style = deviceTypeStyle[deviceType];
            }
            feature.setStyle(style);
            vectorLayer.getSource().addFeature(feature);
            if(AlltypeVal.indexOf(dtype) != -1 ){
                if( checkeVal.indexOf(dtype) == -1 ){
                    vectorLayer.getSource().removeFeature(feature);
                }
            }
        });
    },
    // 选择事件
    selectEle: function(){
        var sel = this;
        var deviceImage = new ol.style.Icon({src:'../images/device.png'});
        var selectedImage = new ol.style.Icon({src:'../images/device.png',scale:1.2});
        var deviceStyle = new ol.style.Style({image:deviceImage});
        var deviceSelectedStyle = new ol.style.Style({image:selectedImage});

        select = new ol.interaction.Select({
            style: deviceStyle,
            filter: function (feature, layer) {
                return layer == sel.vectorLayer;
            }
        });

        sel.map.addInteraction(select);
        selectedFeatures = select.getFeatures();

        var stroke = new ol.style.Stroke({color: 'rgba(255,0,0,0.8)',width: 2});
        var fill = new ol.style.Fill({color: 'rgba(255,255,255,0.3)'});
        var image = new ol.style.Icon({src:'../images/position.png'});
        var drawImage = new ol.style.Circle({fill: fill, stroke: stroke, radius: 3});

        var shapeStyle = new ol.style.Style({image: image, fill:fill, stroke:stroke});//定义样式
        drawStyle = new ol.style.Style({image: drawImage, fill:fill, stroke:stroke});//定义样式

        drawSource = new ol.source.Vector({wrapX: false});
        drawVector = new ol.layer.Vector({              //在地图上绘制图形的图层
            source: drawSource,
            style:shapeStyle
        });
        sel.map.addLayer(drawVector);

        // 圈选点击事件
        $("#circleSelect").click(function(){
            $(".selectFeature").removeClass("active");
            sel.addInteraction("Circle");
            $("#circleSelect").addClass("active");
        });
        $("#polygonSelect").click(function(){
            $(".selectFeature").removeClass("active");
            sel.addInteraction("Polygon");
            $("#polygonSelect").addClass("active");
        });
        $("#shapeClear").click(function(){
            sel.clearShape();
        });
    },
    addInteraction: function(type) {
        var sel = this;
        if(!type) return;
        selectedFeatures.clear();
        var draw1 = sel.draw;
        if(draw1) map.removeInteraction(draw1);
        drawVector.getSource().clear();
        draw1 = new ol.interaction.Draw({
            source: drawSource,
            type:type,
            style:drawStyle
        });
        sel.map.addInteraction(draw1);

        draw1.on('drawend',function(evt){
            $(".selectFeature").removeClass("active");
            if(type=='Circle'){
                var circle = evt.feature.getGeometry();
                setTimeout(function(){
                    sel.getCircleSelect(circle);
                },300);
                //如果不设置延迟，范围内要素选中后自动取消选中，具体原因不知道
            }
            if(type=='Polygon'){
                var polygon = evt.feature.getGeometry();
                setTimeout(function(){
                    sel.getPolygonSelect(polygon);
                },300);
            }
            sel.map.removeInteraction(draw1);
        });
    },
    selectClear: function(){
        var sel = this;
        var selectedFeatures4 = sel.selectedFeatures;
        select.on('select',function(e){
            selectedFeatures4.clear();
        });
    },
    getCircleSelect: function(polygon) {		// 圈选
        var sel = this;
        var center = polygon.getCenter(),radius = polygon.getRadius(),extent = polygon.getExtent();
        var features = sel.vectorLayer.getSource().getFeaturesInExtent(extent);
        var str = "";
        for(var i=0;i<features.length;i++){
            var newCoords = features[i].getGeometry().getCoordinates();//coords.push(features[0].getGeometry().getCoordinates());
            if(sel.pointInsideCircle(newCoords,center,radius)){
                selectedFeatures.push(features[i]);
                str += "<div class=\"selectedItem\" onclick='mapLoadEvent.showDeviceOnMap(\""+features[i].getId()+"\");'>"+features[i].get("deviceName")+"</div>";
            }
        }
        if(str==""){
            str +="<div class='noSearchResult'>无结果</div>";
        }
        $("#selectedInfoContent").html(str);
        if($("#selectedInfo").css("display")=='none'){
            $("#selectedInfo").css("display",'block');
        }

    },
    getPolygonSelect: function(polygon) {	// 多边形选
        var sel = this;
        var coords = polygon.getCoordinates()[0],extent = polygon.getExtent();
        var features = sel.vectorLayer.getSource().getFeaturesInExtent(extent);
        var str = "";
        for(var i=0;i<features.length;i++){
            var newCoords = features[i].getGeometry().getCoordinates();
            //coords.push(features[0].getGeometry().getCoordinates());
            if(sel.insidePolygon(coords,newCoords)){
                selectedFeatures.push(features[i]);
                str += "<div class=\"selectedItem\" onclick='mapLoadEvent.showDeviceOnMap(\""+features[i].getId()+"\");'>"+features[i].get("deviceName")+"</div>";
            }
        }
        if(str==""){
            str +="<div class='noSearchResult'>无结果</div>"
        }
        $("#selectedInfoContent").html(str);
        if($("#selectedInfo").css("display")=='none'){
            $("#selectedInfo").css("display",'block');
        }
    },
    clearShape: function() {		// 清空形状选择内容
        var sel = this;
        var draw2 = sel.draw;
        selectedFeatures.clear();
        drawVector.getSource().clear();
        if(draw2) sel.map.removeInteraction(draw2);
        $(".selectFeature").removeClass("active");
        $("#selectedInfo").css("display",'none');
    },
    insidePolygon: function(points, testPoint){		// 判断一个点是否在多边形内部;@param points 多边形坐标集合;@param testPoint 测试点坐标;返回true为真，false为假
        var x = testPoint[0], y = testPoint[1];
        var inside = false;
        for (var i = 0, j = points.length - 1; i < points.length; j = i++) {
            var xi = points[i][0], yi = points[i][1];
            var xj = points[j][0], yj = points[j][1];
            var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
            if (intersect) inside = !inside;
        }
        return inside;
    },
    pointInsideCircle:function(point, circle, r){		// 判断一个点是否在圆的内部; @param point  测试点坐标; @param circle 圆心坐标; @param r 圆半径;  返回true为真，false为假
        if (r===0) return false;
        var dx = circle[0] - point[0];
        var dy = circle[1] - point[1];
        return dx * dx + dy * dy <= r * r
    },
    // 点击框选出来的内容
    showDeviceOnMap: function(id){
        var sel = this;
        var feature = sel.vectorLayer.getSource().getFeatureById(id);
        if(feature){
            var coords = feature.getGeometry().getCoordinates();
            map.getView().animate({
                center:coords,
                duration:250
            });
        }
    }
}
//二维地图上的点击事件
var mapClickEvent = {
    clickCoordinate : undefined,
    clickFeature : undefined,
    clickEvent : function(){
        var sel = this;
        sel._leftClickEvent();
        sel._rightClickEvent();
        sel._pointMoveEvent();
    },
    _leftClickEvent : function(){
        var sel = this;
        var map = mapLoadEvent.map;
        //地图 页面点击事件
        map.on("click",function(evt){
            //若在设备选中状态下，进行设备在二维地图上添加
            if(moveDeviceEvent._checkRow && !$.isEmptyObject(moveDeviceEvent._checkRow)){
                $("#map").css({cursor:"auto"});
                //刷新table
                var t = ol.proj.transform(evt.coordinate,projection, projection);
                var checkRow = moveDeviceEvent._checkRow;
                var params = {"mapGuid":mapLoadEvent.clickMap.id,"deviceGuid":checkRow.deviceGuid,"deviceType":checkRow.deviceType,"posX":t[0],"posY":t[1]};
                $.ajax({
                    type : 'post',
                    url :  postUrl+"/mapdevice/add.shtml",
                    data : params,
                    dataType : 'json',
                    success : function(data) {
                        moveDeviceEvent._checkRow = undefined;
                        if(data.code == 1000){
                            layer.closeAll();
                            mapLoadEvent.loadDeviceLayer(mapLoadEvent.clickMap.uuid);
                            moveDeviceEvent.tableRefesh();
                        }else{
                            layer.msg("设备点位添加失败！请联系管理员！",{ icon: 2, time: 1000 }, function(){});
                        }
                    }
                })

            }
            // 右键事件隐藏  没有拖动的点击事件
            mapLoadEvent.menu_overlay.setPosition(undefined);
        });
    },
    _rightClickEvent : function(){
        var sel = this;
        var map = mapLoadEvent.map;
        $(map.getViewport()).on("contextmenu", function(event){
            //屏蔽自带的右键事件
            event.preventDefault();
            //坐标系
            var t = ol.proj.transform(map.getEventCoordinate(event),projection, projection);
            clickCoordinate = t;
            mapClickEvent.clickCoordinate = clickCoordinate;

            var pixel = map.getEventPixel(event.originalEvent);
            var feature = map.forEachFeatureAtPixel(pixel,function(feature){
                return feature;
            });

            clickFeature = feature;
            sel.clickFeature = clickFeature;
            mennu._rightClickShow(feature,event);

        });

    },
    _pointMoveEvent : function(){
        var sel = this;
        var map = mapLoadEvent.map;
        //鼠标移动事件
        map.on('pointermove', function(evt) {
            if(app.appDragFlag){
                return;
            }
            if (evt.dragging) {
                return;
            }
            sel.displayFeatureInfo(evt);
        });
    },
    displayFeatureInfo : function(evt){
        var sel = this;
        var map = mapLoadEvent.map;
        var coordinate = evt.coordinate;
        var pixel = map.getEventPixel(evt.originalEvent);
        var feature = map.forEachFeatureAtPixel(pixel, function (feature) { return feature; });//查询方式有很多
        var content = mapLoadEvent.overlayContent;
        var overlay = mapLoadEvent.overlay;
        if (feature) {
            if(feature.getId()){
                content.innerHTML = '<p>设备信息：</p><code>设备名称：' + toolEvent.emptyString(feature.get("deviceName")) + '</code><br>' +
                    '<code>设备类型：' + toolEvent.emptyString(feature.get("deviceType")) + '</code><br>' +
                    '<code>设备品牌：' + toolEvent.emptyString(feature.get("deviceBrand")) + '</code><br>' +
                    '<code>设备型号：' + toolEvent.emptyString(feature.get("deviceModel")) + '</code><br>';
                overlay.setPosition(coordinate);
            }
        } else {
            content.innerHTML = ' ';
            overlay.setPosition(undefined)
        }

    }

}

//========================================================二维地图上拖动效果============================================
var app = {};
app.Drag = function() {
    ol.interaction.Pointer.call(this, {
        handleDownEvent: app.Drag.prototype.handleDownEvent,
        handleDragEvent: app.Drag.prototype.handleDragEvent,
        handleMoveEvent: app.Drag.prototype.handleMoveEvent,
        handleUpEvent: app.Drag.prototype.handleUpEvent
    });
    this.coordinate_ = null;
    this.cursor_ = 'pointer';
    this.feature_ = null;
    this.previousCursor_ = undefined;
    this.appDragFlag = false;

};
ol.inherits(app.Drag, ol.interaction.Pointer);
app.Drag.prototype.handleDownEvent = function(evt) {
    var overlay = mapLoadEvent.overlay;
    overlay.setPosition(undefined);
    this.appDragFlag = true;
    var map = evt.map;

    var feature = map.forEachFeatureAtPixel(evt.pixel,
        function(feature) {
            return feature;
        });

    if (feature) {
        this.coordinate_ = evt.coordinate;
        this.feature_ = feature;
    }

    return !!feature;
};
app.Drag.prototype.handleDragEvent = function(evt) {
    var deltaX = evt.coordinate[0] - this.coordinate_[0];
    var deltaY = evt.coordinate[1] - this.coordinate_[1];

    var geometry = this.feature_.getGeometry();
    geometry.translate(deltaX, deltaY);

    this.coordinate_[0] = evt.coordinate[0];
    this.coordinate_[1] = evt.coordinate[1];
};
app.Drag.prototype.handleMoveEvent = function(evt) {
    if (this.cursor_) {
        var map = evt.map;
        var feature = map.forEachFeatureAtPixel(evt.pixel,
            function(feature) {
                return feature;
            });
        var element = evt.map.getTargetElement();
        if (feature) {
            if (element.style.cursor != this.cursor_) {
                this.previousCursor_ = element.style.cursor;
                element.style.cursor = this.cursor_;
            }
        } else if (this.previousCursor_ !== undefined) {
            element.style.cursor = this.previousCursor_;
            this.previousCursor_ = undefined;
        }
    }
};
app.Drag.prototype.handleUpEvent = function() {
    this.appDragFlag = false;

    var _clickMap = mapLoadEvent.clickMap;
    var _deviceGuid = this.feature_.get("deviceUuid");
    var _posX = this.coordinate_[0];
    var _posY = this.coordinate_[1];
    Ajax({
        "url":"/mapdevice/upd.shtml",
        "param":{"deviceGuid": _deviceGuid,"mapGuid":_clickMap.id,"posX":_posX,"posY":_posY},
        successBack : function(result){

        }
    });
    this.coordinate_ = null;
    this.feature_ = null;
    return false;
};
var appD = new app.Drag();

//========================================================移动弹出框============================================
var moveDeviceEvent = {
    _table : {},
    _checkRow : {},
    _basicTreeObj : {},
    _basicTable : {},
    _alarmTable : undefined,
    _refrshTable : undefined,
    _fromid : undefined,
    tabLoadInit : function(layid,table){
        var sel = this;
        sel._table = table;
        if(layid == "deviceCameraList"){
            //设备列表
            /*** formid,areaid,tableid,keyType,tableFilter **/
            sel._loadDeviceBasicItem("basic_camera_form","search_camera_dept","device_camera_table","JK","move_device_camera");
        }else if(layid == "deviceDoorList"){
            sel._loadDeviceBasicItem("basic_door_form","search_door_dept","device_door_table","MJ","move_device_door");
        }else if(layid == "deviceTalkHostList"){
            sel._loadDeviceBasicItem("basic_talkHost_form","search_talkHost_dept","device_talkHost_table","DJZJ","move_device_talkHost");
        }else if(layid == "deviceTalkList"){
            sel._loadDeviceBasicItem("basic_talk_form","search_talk_dept","device_talk_table","DJFJ","move_device_talk");
        }else if(layid == "deviceBoradCastList"){
            sel._loadDeviceBasicItem("basic_boradCast_form","search_boradCast_dept","device_boradCast_table","GB","move_device_boradCast");
        }else if(layid == "deviceAlarmList"){
            //报警器item页面
            sel._loadDevcieAlarmItem("device_alarm_form","search_alaram_dept");
        }
        sel.initClickEvent();
    },
    //报警器item页面 列表页面
    _loadDevcieAlarmItem : function(formid,areaid){
        var sel = this;
        sel._fromid = formid;
        //异步加载设备类别
        if(!sel._basicTreeObj[areaid]){
            zNodes = TreeNodesObj._zNodes;
            sel._basicTreeObj[areaid] = initSelectTree(areaid,false,null,sel.ztreeClickCallBack);
        }
        //加载table列表
        sel._loadDeviceAlarmTableList();
    },
    //设备列表记载页面
    _loadDeviceBasicItem : function(formid,areaid,tableid,keyType,tableFilter){
        var sel = this;
        sel._fromid = formid;
        //异步加载设备类别
        if(!sel._basicTreeObj[areaid]){
            zNodes = TreeNodesObj._zNodes;
            sel._basicTreeObj[areaid] = initSelectTree(areaid,false,null,sel.ztreeClickCallBack);
        }
        //加载table列表
        sel._loadDeviceBasicTableList(tableid,keyType,tableFilter);
    },
    _loadDeviceAlarmTableList : function(){
        var sel = this;
        var table = sel._table;
        if(!sel._alarmTable){
            sel._alarmTable = table.render({
                elem: '#device_alarmlist',
                method:'post',
                url: postUrl+'/resWarnDevice/listAlarmDevieNoInMapListGrid.shtml',    //数据接口
                request: {limitName: 'rows'},
                height: 240,
                id:'device_alam_list',
                cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                cols: [[
                    {type: "radio", width:20},
                    {field:'ddaName', width:170, title: '设备名称', align: 'center'},
                    {field:'ddaCode',  width:170, title: '编码', sort: true, align: 'center'},
                    {field:'codeName', width:170, title: '报警类型',sort: true, align: 'center'},
                    {field:'mapName', width:170, title: '区域', align: 'center'}
                ]],
                // skin: 'line', //表格风格
                even: true,
                page: true, //是否显示分页
                limits: [10, 15, 20],
                limit: 10 //每页默认显示的数量
            });
            //以复选框事件为例
            table.on('radio(move_device_alarm)', function(obj){
                var data = obj.data;
                var _cur_url = "../images/cur-img/cur_bj.png";
                $("#map").css({cursor:"url("+_cur_url+"),auto"});
                data.deviceType = 2;
                moveDeviceEvent._checkRow = data;
            });
        }
        sel._refrshTable = sel._alarmTable;
    },
    //加载table列表
    _loadDeviceBasicTableList : function(tableid,keyType,tableFilter){
        var sel = this;
        var table = sel._table;
        if(!sel._basicTable[tableid]){
            sel._basicTable[tableid] = table.render({
                elem: '#'+tableid,
                method:'post',
                url: postUrl+'/basicDevice/listDevieNoInMapListGrid.shtml',    //数据接口
                request: {limitName: 'rows'},
                where : {"keyType":keyType},
                height: 240,
                cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                cols: [[
                    {type: "radio", width:20},
                    {field:'dbcName', width:170, title: '设备名称', align: 'center'},
                    {field:'drBrand', width:170, title: '设备品牌', align: 'center'},
                    {field:'drModel', width:170, title: '设备型号', align: 'center'},
                    {field:'mapName',  width:170, title: '区域', sort: true, align: 'center'}
                ]],
                // skin: 'line', //表格风格
                even: true,
                page: true, //是否显示分页
                limits: [10, 15, 20],
                limit: 10 //每页默认显示的数量
            });
            var cur_url_obj = {
                "JK":"../images/cur-img/cur_sxj.png",
                "DW":"../images/cur-img/cur_dw.png",
                "BJ":"../images/cur-img/cur_bj.png",
                "DJZJ":"../images/cur-img/cur_dj.png",
                "DJFJ":"../images/cur-img/cur_djfj.png",
                "MJ":"../images/cur-img/cur_mj.png",
                "MJKZQ":"../images/cur-img/cur_mjkz.png",
                "GB":"../images/cur-img/cur_gb.png"
            };
            //以复选框事件为例
            table.on('radio('+tableFilter+')', function(obj){
                var data = obj.data;
                var _cur_url = cur_url_obj[data.dtTcode]?cur_url_obj[data.dtTcode]:"";
                $("#map").css({cursor:"url("+_cur_url+"),auto"});
                data.deviceType = 1;
                moveDeviceEvent._checkRow = data;
            });
        }
        sel._refrshTable = sel._basicTable[tableid];
    },
    tableRefesh : function(){
        var sel = this;
        var formid = sel._fromid;
        var searchFormfiled = $("#"+formid).find("[lay-type='search']");
        var seachrField = {};
        $.each(searchFormfiled,function(index){
            var _temp = searchFormfiled[index];
            if( $(_temp).hasClass("select-tree") ){
                var ids = getSelectItems(_temp.id).ids;
                seachrField[$(_temp).attr("name")] = ids;
            }else{
                seachrField[_temp.name] = _temp.value;
            }
        });
        var table = sel._table;
        var _refrshTableId = sel._refrshTable.config.id;
        table.reload(_refrshTableId,{
            page: {
                curr: 1
            },
            where : seachrField
        });
    },
    clearForm : function(id){
        $("#"+id)[0].reset();
        var selectTree = $("#"+id).find(".select-tree");
        for(var i=0;i<selectTree.length;i++){
            var _selectTreeId = selectTree[i].id;
            cleanSelectItems(_selectTreeId);
        }
    },
    ztreeClickCallBack : function(event, treeId, treeNode){
        var ztreeObj = $.fn.zTree.getZTreeObj(treeId);
        //根节点判断
        if(treeNode.isParent){
            ztreeObj.expandNode(treeNode,treeNode.isHidden);
        }else{
            onClick(event, treeId, treeNode);
        }
    },
    initClickEvent : function(){
        $(".sq").click(function(){
            if($(this).hasClass("sq")){
                $(this).attr({"class":"dragBtn zk", "title":"展开"});
                $(this).text("＋");
                $(".drag-content").slideUp();
            }else {
                $(this).attr({"class":"dragBtn sq", "title":"收起"});
                $(this).text("-");
                $(".drag-content").slideDown();
            }
        });

        $(".close").click(function(){
            $("#drag-main").hide();
        });

        //弹出框拖动
        $("#drag-title").mousedown(function(e){
            moveDeviceEvent.cancleclick = false;
            $(this).css("cursor","move");

            //var offset = $(this).parent("#drag-main").offset();
            var offset = $("#drag-main").position();
            var x = e.pageX;
            var y = e.pageY;
            var p_x = Math.round(offset.left);
            var p_y = Math.round(offset.top);

            $(document).bind("mousemove",function(ev){
                if(moveDeviceEvent.cancleclick){
                    return;
                }
                $("#drag-main").stop();
                var _x = ev.pageX - x;
                var _y = ev.pageY - y;
                var _mv_x =  p_x + _x,_mv_y = p_y + _y;
                if(_mv_x < 0){
                    _mv_x = 0;
                }
                if (_mv_y < 0){
                    _mv_y = 0;
                }
                $("#drag-main").animate({left:_mv_x+"px",top:_mv_y +"px"},10);
            });
        });

        $(document).mouseup(function(){
            $("#drag-title").css("cursor","default");
            moveDeviceEvent.cancleclick = true;
        });
    }
};

//===============================================设备相关操作方法=======================================
var layopenEvent = {
    //用于设备的新增修改页面
    loadOpen : function(layer,form,layParams){
        layer.open({
            type : 1,
            title: layParams.titleName,
            area: "700px",
            btn: ["确定", "取消"],
            content: "<div id='loadDeviceEvent'></div>",
            success :  function(layero, index){
                $("#loadDeviceEvent").load(layParams.loadUrl+" #"+layParams.loadDivId,function(){
                    deviceInfoAddEvent.layer = layer;
                    deviceInfoAddEvent.form = form;
                    deviceInfoAddEvent.loadMethod(layParams.loadFormid,layParams.typeCode,layParams.layYesFuncParams,layParams.deviceType);
                });
            },
            yes: function(index, layero){
                layero.find("[lay-submit]").click();
            }


        });
    }
}

//设备事件相关放
var deviceInfoAddEvent = {
    loadMethod : function(fromid,typecode,layYesFuncParams,deviceType,loadFormFilter){
        var sel = this;
        var form = deviceInfoAddEvent.form;
        deviceInfoAddEvent.typeCode = typecode;
        deviceInfoAddEvent.fromid 	= fromid;
        sel._loadDeviceParams(typecode,fromid,layYesFuncParams,deviceType,loadFormFilter);
        form.render();
    },
    _loadDeviceParams : function(typeCode,fromid,layYesFuncParams,deviceType){
        var sel = this;
        this._loadParamViews(typeCode);
        var feature = layYesFuncParams.clickFeature;
        if(feature && feature.getId()){
            //修改
            sel._loadUpdTempleInfo(feature,fromid);
            sel._loadBindUpdSubmitConfig(typeCode,fromid,layYesFuncParams,deviceType);
        }else{
            //新增
            sel._loadBindSubmitConfig(typeCode,fromid,layYesFuncParams,deviceType);
        }

    },
    _loadUpdTempleInfo : function(feature,fromid){
        var typeCode = feature.get("typeCode");
        var url = "/basicDevice/getDetailDeviceinfo/camera.shtml";
        if(typeCode == "JK"){
            //form表单提交事件
            url = "/basicDevice/getDetailDeviceinfo/camera.shtml"
        }else if(typeCode == "MJ"){
            url = "/basicDevice/getDetailDeviceinfo/door.shtml"
        }else if(typeCode == "DJZJ"){
            url = "/basicDevice/getDetailDeviceinfo/hostTalk.shtml"
        }else if(typeCode == "DJFJ"){
            url = "/basicDevice/getDetailDeviceinfo/extensionTalk.shtml"
        }else if(typeCode == "GB"){
            url = "/basicDevice/getDetailDeviceinfo/broadcast.shtml"
        }else if(typeCode == "ALARM"){
            url = "/basicDevice/getDetailDeviceinfo/alaram.shtml"
        }
        var detailInfo = deviceInfoAddEvent._AjaxSubmit(url,{"deviceGuid" : feature.get("deviceUuid")});
        if(detailInfo.code == 1000){
            deviceInfoAddEvent.loadTempleForUpdateView(feature.get("deviceUuid"),fromid);
            layerMethod.uploadDataShow(fromid,detailInfo.data);
        }else{
            console.info("设备未查询到具体信息！！");
        }



    },
    loadTempleForUpdateView : function(deviceUuid,fromid){
        $("#"+fromid).find("div.layui-form-item[lay-templeAddFlag]").remove();
        var resultTempleInfo = deviceInfoAddEvent._AjaxSubmit("/basicDevcieTempleInfo/getTempleInfoList.shtml",{"dmfDbcuuid":deviceUuid});
        var templeList = resultTempleInfo.data;
        //创建div  一行放2个参数
        var divElement;
        for(var i=0;i<templeList.length;i++){
            var _temple = templeList[i];
            var _jsonStr = encodeURIComponent(encodeURIComponent(JSON.stringify(_temple)));
            if( i%2 == 0){
                divElement = $("<div class='layui-form-item' lay-templeAddFlag></div>");
            }
            var labelEl         = $("<label class='layui-form-label'>"+_temple.dmfName+"：</label>");
            var divInputEle     = $("<div class='layui-input-inline'></div>");
            var divInputValEle  = $("<input type='text' class='layui-input' params='"+_jsonStr+"' uuid='"+_temple.dmpUuid+"' paramName='"+_temple.dmfName+"' name='"+_temple.dmfParam+"' value='"+_temple.dmfValue+"' lay-json />");
            divInputEle.append(divInputValEle);
            divElement.append(labelEl);
            divElement.append(divInputEle);
            if( i%2 == 1 || i==(templeList.length-1) ){
                $("#"+fromid).append(divElement);
            }
        }
    },
    _formBindAlarmSummit : function(fromid,url,layYesFuncParams,deviceType){
        var form = deviceInfoAddEvent.form;
        //var laysubmitfilter = $("[lay-submit]").attr("lay-filter");
        var laysubmitfilter = $("#"+fromid+" [lay-submit]").attr("lay-filter");
        form.on("submit("+laysubmitfilter+")",function(data){
            var layer = deviceInfoAddEvent.layer;
            layerMethod.setTableSelectVal(fromid);
            var dataJson = $("#"+fromid).serialize();
            var _bindDeviceUuid = $("#ddaDbcuuid").val();
            //1.添加设备记录
            //2.存入二维地图设备关联表中 判断是否选中了对应的关联设备  若选中对应的关联设，不插入关联表中，未选中则插入关联表中
            var _addDeviceObj = deviceInfoAddEvent._AjaxDeviceSubmit(url,dataJson);
            if(_addDeviceObj){
                if(_bindDeviceUuid){
                    layer.msg("联动报警器新增成功！", {icon: 2,time: 1000},function(){
                        layer.closeAll();
                    });
                }else{
                    deviceInfoAddEvent._AjaxMapDeviceSubmit("/mapdevice/add.shtml",_addDeviceObj.ddaUuid,layYesFuncParams,deviceType);
                }
            }else{
                console.info("未返回加载的设备对象信息");
            }
            return false;
        });
    },
    _formBindSummit : function(fromid,url,layYesFuncParams,deviceType){
        var form = deviceInfoAddEvent.form;
        var laysubmitfilter = $("#"+fromid+" [lay-submit]").attr("lay-filter");
        form.on("submit("+laysubmitfilter+")",function(data){
            var jsonArray =  layerMethod.getJsonVal(fromid,"lay-json");
            $("[lay-valueJson]").val(JSON.stringify(jsonArray));
            var dataJson = $("#"+fromid+" [lay-json!='']").serialize();
            //1.添加设备记录
            //2.存入二维地图设备关联表中
            var _addDeviceObj = deviceInfoAddEvent._AjaxDeviceSubmit(url,dataJson);
            if(_addDeviceObj){
                deviceInfoAddEvent._AjaxMapDeviceSubmit("/mapdevice/add.shtml",_addDeviceObj.dbcUuid,layYesFuncParams,deviceType);
            }else{
                console.info("未返回加载的设备对象信息");
            }
            return false;
        });
    },
    _formBindUpdSummit : function(fromid,url,layYesFuncParams,deviceType){
        var layer = deviceInfoAddEvent.layer;
        var form = deviceInfoAddEvent.form;
        //var laysubmitfilter = $("[lay-submit]").attr("lay-filter");
        var laysubmitfilter = $("#"+fromid+" [lay-submit]").attr("lay-filter");
        form.on("submit("+laysubmitfilter+")",function(data){
            debugger;
            var jsonArray =  layerMethod.getJsonVal(fromid,"lay-json");
            $("[lay-valueJson]").val(JSON.stringify(jsonArray));
            var dataJson = $("#"+fromid+" [lay-json!='']").serialize();
            var updResult = deviceInfoAddEvent._AjaxSubmit(url,dataJson);
            if(updResult.data.success){
                var feature = layYesFuncParams.clickFeature;
                var updMapParams = {"mapGuid":mapLoadEvent.clickMap.id , "deviceGuid":feature.get("deviceUuid"),"deviceType":deviceType};
                var mapDevcieUpd =  deviceInfoAddEvent._AjaxSubmit("/mapdevice/updDeviceByMapDevice.shtml",updMapParams);
                if(mapDevcieUpd.code == 1000){
                    layer.msg("修改成功",{ icon: 1, time: 1000 }, function(){
                        //刷新页面
                        mapLoadEvent.loadDeviceLayer(mapLoadEvent.clickMap.uuid);
                        layer.closeAll();
                    });
                }else{
                    layer.alert(mapDevcieUpd.msg, {icon: 2});
                }
            }else{
                var errorMsg = updResult.data.msg;
                layer.alert(errorMsg, {icon: 2});
                console.info("修改失败",updResult.data);
            }
            return false;
        });
    },
    _AjaxSubmit : function(url,ajaxParams){
        var obj = undefined;
        Ajax({
            "url":url,
            "isdefult":true,
            "param":ajaxParams,
            successBack: function(adata){
                obj = adata;
            }
        });
        return obj;
    },
    _AjaxDeviceSubmit : function(url,ajaxParams){
        var layer = deviceInfoAddEvent.layer;
        var result = deviceInfoAddEvent._AjaxSubmit(url,ajaxParams);
        console.info("设备插入返回",result);
        if(result.data.success==true){
            return result.data.data;
        }else{
            layer.alert(result.data.msg, {icon: 2});
            return undefined;
        }
    },
    _AjaxMapDeviceSubmit : function(url,deviceGuid,layYesFuncParams,deviceType){
        var layer = deviceInfoAddEvent.layer;
        if(clickMap){
            var clickCoordinate = layYesFuncParams.clickCoordinate;
            var params = {"mapGuid":mapLoadEvent.clickMap.id,"deviceGuid":deviceGuid,"deviceType":deviceType,"posX":clickCoordinate[0],"posY":clickCoordinate[1]};
            var result = deviceInfoAddEvent._AjaxSubmit(url,params);
            if(result.code == 1000){
                layer.msg(result.msg,{ icon: 1, time: 1000 }, function(){
                    //刷新页面
                    mapLoadEvent.loadDeviceLayer(mapLoadEvent.clickMap.uuid);
                    moveDeviceEvent.tableRefesh();
                    layer.closeAll();
                });
            }else{
                layer.alert(result.msg, {icon: 2});
            }
        }else{
            layer.alert("选择地图无效", {icon: 2});
        }

    },
    clickMethod : function(event, treeId, treeNode){
        deviceInfoAddEvent.basicTreeClick(event, treeId, treeNode , "deviceTreeToolEvent.addDeviceOrder");
    },
    clickMethodForBrand : function(event, treeId, treeNode){
        deviceInfoAddEvent.basicTreeClick(event, treeId, treeNode ,"deviceTreeToolEvent.loadTempleForAddView");
    },
    basicTreeClick : function(event, treeId, treeNode, fn ){
        var ztreeObj = $.fn.zTree.getZTreeObj(treeId);
        if(treeNode.isParent){
            ztreeObj.expandNode(treeNode,treeNode.isHidden);
        }else{
            onClick(event, treeId, treeNode);
            //给隐藏域赋值
            var tid = treeId.replace("Tree","");
            var hideTreeInputs = $("[lay-hidenTree='"+tid+"']");
            $.each(hideTreeInputs,function(index){
                var _name = this.getAttribute("lay-hidenTreeName");
                $(this).val(treeNode[_name]);
            });
            if(typeof fn == "function"){
                fn(treeNode);
            }else if(typeof fn == "string"){
                var callback = eval(fn);
                new callback(treeNode);
            }
        }
    } ,
    _setClickZtreeMap : function(ztreeid){
        var sel = this;
        var treeObj = $.fn.zTree.getZTreeObj(ztreeid+"Tree");
        treeObj.selectNode(clickMap);
        sel.clickMethod(null,ztreeid+"Tree",clickMap);
    },
    _loadDoorControllTable : function(tableSelect){
        tableSelect.render({
            elem: '#addUpd_dddControlluuid',
            checkedKey: 'dbcUuid',
            searchKey: 'dbcName',
            searchPlaceholder: '关键词搜索',
            table: {
                method: 'post',
                request: { limitName: 'rows' },
                url: postUrl+"/basicDevice/listBsicDeviceInfoGrid/doorcontrol.shtml",
                height: 300,
                area:['300px','300px'],
                cols: [[
                    {type: "radio", width: "5%"},
                    {field: "dbcName", title:"设备名称", width: "20%"},
                    {field: "dtName", title:"设备类型", width: "35%"},
                    {field: "mapName", title:"所属区域", width: "40%"}
                ]],
                page: true
            },
            done: function (elem, data) {
                var selectName = [];
                layui.each(data.data, function (index, item) {
                    selectName.push(item.dbcName);
                });
                elem.val(selectName.join("，"));
                $("#dddControlluuid_hid").val($('#addUpd_dddControlluuid').attr("ts-selected"));
            }
        });
    },
    _loadTalkExtensionControllTable : function(tableSelect){
        tableSelect.render({
            elem: '#addUpd_ddtHostuuid',
            checkedKey: 'dbcUuid',
            searchKey: 'dbcName',
            searchPlaceholder: '关键词搜索',
            table: {
                method: 'post',
                request: { limitName: 'rows' },
                url: postUrl+"/basicDevice/listBsicDeviceInfoGrid/hostTalk.shtml",
                height: 300,
                area:['300px','300px'],
                cols: [[
                    {type: "radio", width: "5%"},
                    {field: "dbcName", title:"设备名称", width: "20%"},
                    {field: "dtName", title:"设备类型", width: "35%"},
                    {field: "mapName", title:"所属区域", width: "40%"}
                ]],
                page: true
            },
            done: function (elem, data) {
                var selectName = [];
                layui.each(data.data, function (index, item) {
                    selectName.push(item.dbcName);
                });
                elem.val(selectName.join("，"));
                $("#ddtHostuuid_hid").val($('#addUpd_ddtHostuuid').attr("ts-selected"));
            }
        });
    },
    _loadAlaramDeviceTable : function(tableSelect){
        tableSelect.render({
            elem: '#ddaDbcuuid',
            checkedKey: 'dbcUuid',
            searchKey: 'dbcName',
            searchPlaceholder: '关键词搜索',
            table: {
                method: 'post',
                request: { limitName: 'rows' },
                url: postUrl+"/basicDevice/listBsicDeviceInfoGrid/.shtml",
                height: 300,
                area:['300px','300px'],
                cols: [[
                    {type: "radio", width: "5%"},
                    {field: "dbcName", title:"设备名称", width: "20%"},
                    {field: "dtName", title:"设备类型", width: "35%"},
                    {field: "mapName", title:"所属区域", width: "40%"}
                ]],
                page: true
            },
            done: function (elem, data) {
                var selectName = [];
                layui.each(data.data, function (index, item) {
                    selectName.push(item.dbcName);
                });
                elem.val(selectName.join("，"));
                $("#ddaDbcuuid_id").val($('#ddaDbcuuid').attr("ts-selected"));
            }
        });
    }
}


var deviceTreeToolEvent = {
    addDeviceOrder : function(treeNode){
        var typeCode = deviceInfoAddEvent.typeCode;
        Ajax({
            "url":"/basicDevice/getNextOrder.shtml",
            "type": "post",
            "param":{"dbcDept":treeNode.id,"dbcTypeuuid":typeCode},
            successBack: function(data){
                $("[lay-deptOrder]").val(data);
            }
        });
    },
    loadTempleForAddView : function(treeNode){
        var brandUuid = treeNode.id;
        var fromid = deviceInfoAddEvent.fromid;
        $("#"+fromid).find("div.layui-form-item[lay-templeAddFlag]").remove();
        var templeList =  deviceTreeToolEvent.laodTempleByBrandUuid(brandUuid);
        //创建div  一行放2个参数
        var divElement;
        for(var i=0;i<templeList.length;i++){
            var _temple = templeList[i];
            var _jsonStr = encodeURIComponent(encodeURIComponent(JSON.stringify(_temple)));
            if( i%2 == 0){
                divElement = $("<div class='layui-form-item' lay-templeAddFlag ></div>");
            }
            var labelEl         = $("<label class='layui-form-label'>"+_temple.dmpName+"：</label>");
            var divInputEle     = $("<div class='layui-input-inline'></div>");
            var divInputValEle  = $("<input type='text' class='layui-input' params='"+_jsonStr+"' uuid='"+_temple.dmpUuid+"' paramName='"+_temple.dmpName+"' name='"+_temple.dmpParam+"' lay-json />");
            divInputEle.append(divInputValEle);
            divElement.append(labelEl);
            divElement.append(divInputEle);
            if( i%2 == 1 || i==(templeList.length-1) ){
                $("#"+fromid).append(divElement);
            }
        }
    },
    laodTempleByBrandUuid : function(brandUuid){
        var deviceType = [];
        Ajax({
            "url":"/basicDevcieTemple/getTempleListByBrand.shtml",
            "type": "post",
            "param":{"dmpDruuid":brandUuid},
            successBack: function(data){
                deviceType = data;
            }
        });
        return deviceType;
    }
}

var layerMethod = {
    getJsonVal : function(formid,filter){
        var jsonList = $("#"+formid).find("["+filter+"]");
        var jsonArray = new Array();
        for(var i=0;i<jsonList.length;i++){
            var _t = jsonList[i];
            var _name = _t.name;
            var _val = _t.value;
            var _params = _t.getAttribute("paramName");
            var _uuid = _t.getAttribute("uuid");
            //var _paramsObj = JSON.parse(decodeURIComponent(decodeURIComponent(_params)));
            var _obj = {"jsonParam":_name,"jsonValue":_val,"jsonName":_params,"jsonUuid":_uuid};
            jsonArray.push(_obj);
        }
        return jsonArray;
    },
    setTableSelectVal : function(fromid){
        var selectTableInput = $("#"+fromid).find("input[lay-tableSelect]");
        $.each(selectTableInput,function(index){
            var _item = this;
            var _val = _item.value;
            var _selectTableVal = $("#"+fromid).find("input[lay-tableSelectVal][lay-tableSelectId='"+_item.id+"']");
            if(_val){
                _selectTableVal.val(_item.getAttribute("ts-selected"));
            }else{
                _selectTableVal.val("");
            }

        });

    },
    uploadDataShow : function(formid,data){
        var form = deviceInfoAddEvent.form;
        var formlayer = $("#"+formid).attr("lay-filter");
        var selectTree = $("#"+formid).find(".select-tree");
        for(var i=0;i<selectTree.length;i++){
            var _selectTreeId = selectTree[i].id;
            var _layUploadConfig = selectTree[i].getAttribute("lay-uploadfield");
            var _layUplaodobj =  eval('('+_layUploadConfig+')');
            if(_layUplaodobj && data[_layUplaodobj.idfield]){
                var _val = templeShow(_layUplaodobj.tmpfield,data);
                setTreeValue(_selectTreeId,_val,data[_layUplaodobj.idfield]);
            }
        }
        var tableSelect = $("#"+formid).find("[lay-tableSelect]");
        $.each(tableSelect,function(index){
            var _tiem = this;
            var _itemNameParam = _tiem.getAttribute("lay-tableSelectName");
            _tiem.value = (data[_itemNameParam]?data[_itemNameParam]:"");
        });
        form.val(formlayer,data);
        form.render("select");
    }
};


/**二维地图抛给外部的调用方法***/
var mapEventInterface = {
    loadOpneLayer : function(node){
        mapLoadEvent.loadImageLayer(node);
        mapLoadEvent.loadDeviceLayer(node.uuid);
        mapLoadEvent.clearShape();
    },
    /**根据设备uuid 定位掉具体的点位信息和图标显示**/
    pointIntoDeciceGuid : function(deviecGuid){
        //根据设备uuid定位到对应的二维地图图层
        var resultData = deviceInfoAddEvent._AjaxSubmit("/mapdevice/getDevcieDetailInfo.shtml",{"deviceGuid":deviecGuid});
        if(!resultData){
            console.info("二维地图上没有配置对应的设备信息");
            return false;
        }
        var shearTreeNode = mapEventInterface._getShareTreeNode(resultData.mapGuid);
        mapEventInterface.loadOpneLayer(shearTreeNode);
        //1、直接定位到坐标 显示闪烁图层
        var point_overlay = mapLoadEvent.pointShareOverlay;
        mapLoadEvent.showDeviceOnMap(deviecGuid);
        point_overlay.getElement().style.display="block";
        point_overlay.setPosition([resultData.posX, resultData.posY]);
        var feature = mapLoadEvent.vectorLayer.getSource().getFeatureById(deviecGuid);
        return feature;
    },
    _getShareTreeNode : function(mapGuid){
        //var treeNode = zTreeLoadEvent.zTreeObj.getNodes();
        var treeNode = TreeNodesObj._zNodes;
        var shearTreeNode = null;
        $.each(treeNode,function(index){
            var _item = this;
            if(_item.id == mapGuid){
                shearTreeNode = _item;
                return false;
            }

        });
        return shearTreeNode;
    }
}

/**
 * Created by loutianxi on 2019/12/26.
 */
